//
//  BMAccountManager.m
//  特种车调度
//
//  Created by 陈宇 on 15/9/2.
//
//

//#import <BaiduMapAPI/BMKGeometry.h>
#import "BMAccountManager.h"
//#import "APService.h"
#import "BMRequest.h"
#import "BMResponse.h"

NSString *const kLocationChangedNotification = @"kLocationChangedNotification";

#define kUserPath   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"user"]

@interface BMAccountManager () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *manager;

@end

@implementation BMAccountManager

kSingletonM

//- (instancetype)init
//{
//    if (self = [super init]) {
//        _user = [NSKeyedUnarchiver unarchiveObjectWithFile:kUserPath];
//        if (_user) {
//            [APService setAlias:[@(_user.ID) description] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
//            BMLog(@"注册极光别名:%lu", _user.ID);
//        }
//        
//        self.manager = [[CLLocationManager alloc] init];
//        self.manager.delegate = self;
//        if ([self.manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
//            [self.manager requestWhenInUseAuthorization];
//        }
//        _location = self.manager.location.coordinate;
//        [self.manager startUpdatingLocation];
//    }
//    return self;
//}

//- (void)setUser:(User *)user
//{
//    if (user == nil) {
//        return;
//    }
//    _user = user;
//    [APService setAlias:[@(_user.ID) description] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
//    BMLog(@"注册极光别名：%lu", _user.ID);
//    [NSKeyedArchiver archiveRootObject:_user toFile:kUserPath];
//}

- (BOOL)isLogin
{
    return _user != nil;
}

//- (void)logout
//{
//    BMLog(@"注销极光别名：%lu", _user.ID);
//    _user = nil;
//    [APService setAlias:@"" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
//    NSFileManager *fm = [NSFileManager defaultManager];
//    if ([fm fileExistsAtPath:kUserPath]) {
//        [fm removeItemAtPath:kUserPath error:nil];
//    }
//}

- (void)updateInfo
{
    if (!_user) {
        return;
    }
    BMRequest *request = [BMRequest requestWithPath:@"getOwnerOrDispatcherById.htm" contentKey:@"info"];
    request.params = @{@"id": @([BMAccountManager sharedInstance].user.ID), @"role": kRole};
    [User postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        if (response.status == kResultOK) {
            self.user = response.result;
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self.manager stopUpdatingLocation];
    CLLocation *location = locations.firstObject;
    if (location) {
        _location = [self convertToBaiduCood:location.coordinate];
        [[NSNotificationCenter defaultCenter] postNotificationName:kLocationChangedNotification object:nil];
    }
}

- (void)updateLocation {
    [self.manager startUpdatingLocation];
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet *)tags alias:(NSString *)alias {
    NSString *callbackString = [NSString stringWithFormat:@"%d, \ntags: %@, \nalias: %@\n", iResCode, [self logSet:tags], alias];
    BMLog(@"TagsAlias回调:%@", callbackString);
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logSet:(NSSet *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

//- (CLLocationCoordinate2D)convertToBaiduCood:(CLLocationCoordinate2D)origin {
//    return BMKCoorDictionaryDecode(BMKConvertBaiduCoorFrom(origin, BMK_COORDTYPE_GPS));
//}

@end
